// format date
const formatDate = function (time) {
    var 
    	now = new Date(),
        old = new Date(time),
        timer = new Date(now.toLocaleDateString()).getTime(),
        hms = old.toTimeString().slice(0, 5)
    ;

    switch(true) {
        case now.getFullYear() !== old.getFullYear():
            var t = old.toLocaleDateString().split('/');
            return `${ t[0] }年${ t[1] }月${ t[2] }日${ hms }`;
        case timer - time <= 86400000:
            if(old.getDate() === now.getDate()) {
                return '今天 ' + hms;
            } else {
                return '昨天 ' + hms;
            }
        case timer - time <= 86400000 * 7:
            var _old = old.getDay(),
                _now = now.getDay(),
                week = ['一', '二', '三', '四', '五'];
            ;
            if(_old * (_now - _old) > 0){
                return '星期' + week[_old - 1] + hms;
            }
        default:
            return `${ (old.getMonth() + 1) }月${ old.getDate() }日${ hms }`;
        ;
    }
};

// get environment
const getEnv = function getEnv() {
    try {
        if(self && self.self === self) {
            getEnv = x => true;
            return true;
        } else {
            getEnv = x => false;
            return false;
        }
    } catch(e) {
        getEnv = x => false;
        return false;
    }
};

// simple log tool
const print = function (params, color) {
    if(getEnv()) {
        // window下
        color = color || '#0089ff';
        if(params && typeof params === 'object') {
            console.table(params);
        } else {
            console.log('%c' + params, `
                font-size: 16px;
                color: white;
                background-color: ${ color }
            `);
        }
    } else {
        // node下
        color = `[${ color || '92' }m`;
        if(params && typeof params === 'object') {
            console.log(params);
        } else {
            console.log('\033' + color + params + ' \033[39m');
        }
    }
};


// get animation event name
const whichTransitionAndAnimationEvent = function () {
    var 
        el = document.createElement('fakeelement'),
        transitions = {
            'transition': 'transitionend',
            'OTransition': 'oTransitionEnd',
            'MozTransition': 'transitionend',
            'WebkitTransition': 'webkitTransitionEnd'
        },
        result = {
            transition: '',
            animation: ''
        }
    ;

    for(var t in transitions) {
        if(el.style[t] !== undefined) {
            result.transition = transitions[t];
            break;
        }
    }
    
    if(el.style['animation'] !== undefined) {
        result.animation = 'animationend';
    } else if(el.style['webkitAnimation'] !== undefined) {
        result.animation = 'webkitAnimationEnd';
    }
    return result;
};


// format money digit
const formatNumberGrounpWithThree = function (num, groupLength = 3) {
    var 
        numberString = num + '',
        stringLength = numberString.length
    ;

    if(stringLength < groupLength + 1) {
        return numberString;
    }

    var 
        remainder = stringLength % groupLength,
        headerString = remainder ? numberString.slice(0, remainder) + ',' : '',
        reg = new RegExp('(\\d{' + groupLength + '}(?!$))', 'g')
    ;

    numberString = headerString + numberString.slice(remainder).replace(reg, '$1,');
    return numberString;
};

// create object with namespace
const namespace = function(name) {
    var 
        parts = name.split('.'),
        current = this
    ;

    for(var i = 0, len = parts.length; i < len; i++) {
        if(!current[parts[i]]) {
            current[parts[i]] = {};
        }
        current = current[parts[i]];
    }
    return this;
};

// format decimal
const formatDecimal = function(number, length = 2) {
    if(length <= 0) {
        return Math.round(number) + '';
    }

    var 
        abs = Math.abs(number),
        int = Math.floor(abs),
        dot = abs - int,
        sym = number < 0 ? '-' : '',
        tmp = 0,
        dotStr = ''
    ;

    tmp = Math.round((1 + dot) * Math.pow(10, length));
    dotStr = (tmp + '').slice(0 - length);
    return sym + int + '.' + dotStr;
};

const modifyUrlParmas = function (url, paramsName, paramsValue) {
    var 
        returnUrl = '',
        params = `${paramsName}=${paramsValue}`,
        paramsSymbol = '',
        reg = null
    ;

    if (url.indexOf(paramsName) === -1) {
        paramsSymbol = url.indexOf('?') === -1 ? '?' : '&';
        returnUrl = url + paramsSymbol + params;
    } else {
        reg = new RegExp(`${paramsName}=` + '\\w+');
        returnUrl = url.replace(reg, params);
    }
    return returnUrl;
};

const isSupportWebp = function isSupportWebp() {
    if(document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0) {
        isSupportWebp = e => true;
        return true;
    } else {
        isSupportWebp = e => false;
        return false;
    }
};

const changeImageUrlToWebpb = function (url) {
    if(isSupportWebp()) {
        return url.replace(/(\.jpg|\.png)$/, '.webp');
    } else {
        return url;
    }
};

module.exports = {
    getEnv,
    print,
    formatDate,
    formatNumberGrounpWithThree,
    namespace,
    formatDecimal,
    modifyUrlParmas,
    changeImageUrlToWebpb
};